//
//  SCBaseViewController.m
//  Assembly
//
//  Created by 葛悦彣 on 2023/11/9.
//

#import "SCBaseViewController.h"
#import "UIScrollView+EmptyDataSet.h"
#import <CoreLocation/CoreLocation.h>
#import "GRefreshAutoNormalFooter.h"
#import "AppDelegate.h"
#import "GQImageViewer.h"

@interface SCBaseViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate,CLLocationManagerDelegate>


@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) void(^addressBlock)(NSString *);

@property (nonatomic, strong) ACMediaPickerManager *m;

@end

@implementation SCBaseViewController

- (void)setIsWhite:(BOOL)isWhite{
    _isWhite = isWhite;
    if(isWhite){
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    } else {
        if (@available(iOS 13.0, *)) {
            [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDarkContent;
        } else {
            // Fallback on earlier versions
        }
    }
}

- (void)addressWithBlock:(void(^)(NSString*))block{
    self.addressBlock = block;
    if([CLLocationManager locationServicesEnabled] && [CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied) {
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        [self.locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
        self.locationManager.pausesLocationUpdatesAutomatically = NO;
        [self.locationManager startMonitoringSignificantLocationChanges];
        [self.locationManager requestWhenInUseAuthorization];
        
        self.addressStr = @"";
        self.addressBlock = block;
        // 开始定位
        [self.locationManager startUpdatingLocation];
    }else {
        //提示用户无法进行定位操作
        [self.view showWarning:@"无法获得定位,请开启定位权限"];
    }
    
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    NSLog(@"Error:%@",error);
      if(self.addressBlock){
        self.addressBlock(@"未获取到位置信息");
          self.addressBlock = ^(NSString *) {
              NSLog(@"已经走过了");
          };
    }
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
    CLLocation * c = locations.lastObject;
    NSLog(@"当前坐标%@",c);
    [geoCoder reverseGeocodeLocation:[locations lastObject] completionHandler:^(NSArray *placemarks, NSError *error) {
        if(error){
            [[DTKTool getCurrentVC].view showWarning:@"无法获取地址"];
            NSLog(@"%@",error);
            if(self.addressBlock){
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.addressBlock(@"未获取到位置信息");
                    self.addressBlock = ^(NSString *) {
                        NSLog(@"已经走过了");
                    };
                });
            }
        } else {
            CLPlacemark *mark = [placemarks lastObject];
            NSString *cityName = mark.locality;
            NSString *subLocality = mark.subLocality;
            NSString *thoroughfare = mark.thoroughfare;
            NSLog(@"当前的地址是%@",cityName);
            if(cityName.length > 0 && self.addressStr.length < 1){
                self.addressStr = [NSString stringWithFormat:@"%@%@%@",cityName,subLocality,thoroughfare];
                if(self.addressBlock){
                    dispatch_async(dispatch_get_main_queue(), ^{
                        self.addressBlock([NSString stringWithFormat:@"%@%@%@",cityName,subLocality,thoroughfare]);
                        self.addressBlock = ^(NSString *) {
                            NSLog(@"已经走过了");
                        };
                    });
                }
            } else {
                if(self.addressStr.length < 1){
                    [[DTKTool getCurrentVC].view showWarning:@"无法获取地址"];
                    [self.locationManager stopUpdatingLocation];
                }
                if(self.addressBlock){
                    dispatch_async(dispatch_get_main_queue(), ^{
                        self.addressBlock(@"未获取到位置信息");
                        self.addressBlock = ^(NSString *) {
                            NSLog(@"已经走过了");
                        };
                    });
                }
            }
        }
    }];
    //
    [self.locationManager stopUpdatingLocation];
}
-(int)pageNo {
    if(_pageNo == 0){
        _pageNo = 1;
    }
    return _pageNo;
}
-(int)pageSize {
    if(_pageSize == 0){
        _pageSize = 10;
    }
    return _pageSize;
}

-(void)refreshingData{
    self.pageNo = 0;
    [self loadNewData];
}

-(void)addMoreData{
    self.pageNo += 1;
    [self loadNewData];
}
///刷新接口
- (void)loadNewData {
    //    [self.view showBusyHUD];
}

- (void)addFooterView:(MJRefreshComponentAction)Block{
    [self addFooterView:Block andCount:0];
}
- (void)addFooterView:(MJRefreshComponentAction)Block andCount:(int)count {
    GRefreshAutoNormalFooter * footer = [GRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        Block();
    }];
    ///无感知刷新数量
    footer.triggerAutomaticallyRefreshPercent = count;
    self.tableview.mj_footer = footer;
}
- (void)addHeaderView:(MJRefreshComponentAction)Block{
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        Block();
    }];
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
      
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
//    self.isWhite = YES;
    self.StatusBarColor = YES;
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;

    ///默认加入侧滑
    UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(rightPanAction:)];
    [self.view addGestureRecognizer:pan];
    self.view.backgroundColor = KcolorHex(@"#F1F3F9");
    self.edgesForExtendedLayout = UIRectEdgeNone;
}
- (void)popViewController{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)back{
    [self popViewController];
}
///侧滑
- (void)rightPanAction:(UIPanGestureRecognizer *)gest
{
    if(self.shutDownBack){
    } else{
        CGPoint gestPoint = [gest translationInView:self.view];
        if (gestPoint.x > 100) {
            [self back];
        }
    }
}

- (UITableView *)tableview{
    if(!_tableview){
        _tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, kwt(120), SCREEN_WIDTH, SCREEN_HEIGHT - kwt(120)) style:UITableViewStyleGrouped];
        if(self.isTableviewZD){
            _tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, kwt(120), SCREEN_WIDTH, SCREEN_HEIGHT - kwt(120)) style:UITableViewStylePlain];
        }
        _tableview.delegate = self;
        _tableview.dataSource = self;
//        _tableview.backgroundColor =BgColor;
        _tableview.emptyDataSetSource = self;
        _tableview.emptyDataSetDelegate = self;
        _tableview.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
        if (@available(iOS 11.0, *)) {
            _tableview.estimatedRowHeight = 0;
            _tableview.estimatedSectionHeaderHeight = 0;
            _tableview.estimatedSectionFooterHeight = 0;
            _tableview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        if (@available(iOS 15.0, *)) {
            _tableview.sectionHeaderTopPadding = 0;
            _tableview.fillerRowHeight = 0;
        }
        _tableview.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.01)];
        _tableview.sectionHeaderHeight = 0.01;
        _tableview.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.01)];
        _tableview.sectionFooterHeight = 0.01;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor = UIColor.clearColor;
    }
    return _tableview;
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{ return YES; }
- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView {
    if(self.NoDataHidden){
        return  [UIView new];
    }
    //加入你自定义的view
    UIView * noView = [UIView new];
    UIView * NewnoView = [UIView new];
//    NewnoView.backgroundColor = UIColor.whiteColor;
    [noView addSubview:NewnoView];
    [NewnoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_offset(KSCREEN_WIDTH);
        make.center.offset(0);
        make.height.mas_offset(KSCREEN_HEIGHT);
    }];
    UIImageView * noImage = [UIImageView new];
    [noView addSubview:noImage];
    noImage.image = [UIImage imageNamed:@"no_data"];
    [noImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_offset(0);
        make.centerY.mas_offset(-100);
    }];
    
    UILabel * noTitleLab = [UILabel new];
    [noView addSubview:noTitleLab];
    noTitleLab.text = @"暂无数据";
    noTitleLab.font = kCFont(17);
    noTitleLab.textColor = [UIColor colorWithHexString:@"#262626"];
    [noTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(noImage.mas_bottom).offset(30);
        make.centerX.mas_offset(0);
    }];
    
    return noView;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [UIView new];
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 0;
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    return [UITableViewCell new];
}

- (void)openImgArray:(NSArray *)array andindex:(int)index {
    [[GQImageViewer sharedInstance] setImageArray:array textArray:nil];//这是数据源
    [GQImageViewer sharedInstance].selectIndex = index;//设置选中的索引
    [GQImageViewer sharedInstance].configure = ^(GQImageViewrConfigure *configure) {//设置配置信息
        [configure configureWithImageViewBgColor:[UIColor blackColor]
                                 textViewBgColor:nil
                                       textColor:[UIColor whiteColor]
                                        textFont:[UIFont systemFontOfSize:12]
                                   maxTextHeight:100
                                  textEdgeInsets:UIEdgeInsetsMake(5, 5, 5, 5)
                                       scaleType:GQImageViewerScaleTypeEqualWidth];
    };
    [[GQImageViewer sharedInstance] showInView:self.view animation:YES];
}

- (ACMediaPickerManager *)openXJandBlock:(void(^)(NSArray<ACMediaModel *> * list))block{
    ACMediaPickerManager * mgr = [[ACMediaPickerManager alloc] init];
    // 定制外观
    mgr.naviBgColor = [UIColor whiteColor];
    mgr.naviTitleColor = [UIColor blackColor];
    mgr.naviTitleFont = [UIFont boldSystemFontOfSize:18.0f];
    mgr.barItemTextColor = [UIColor blackColor];
    mgr.barItemTextFont = [UIFont systemFontOfSize:15.0f];
    mgr.statusBarStyle = UIStatusBarStyleDefault;
    ///是否需要录像
    mgr.allowTakeVideo = NO;
    ///选择图片
    mgr.allowPickingImage = YES;
    //  _mgr.allowPickingGif = YES;
    mgr.maxImageSelected = 1;
    mgr.videoMaximumDuration = 15;
    mgr.pickerSource = ACMediaPickerSourceFromCamera;
    mgr.didFinishPickingBlock = ^(NSArray<ACMediaModel *> * _Nonnull list) {
        dispatch_async(dispatch_get_main_queue(), ^{
            block(list);
        });
    };
    [mgr picker];
    self.m = mgr;
    return mgr;
}

- (ACMediaPickerManager *)openXJWithType:(ACMediaPickerSource)type  andBlock:(void(^)(NSArray<ACMediaModel *> * list))block{
    ACMediaPickerManager * mgr = [[ACMediaPickerManager alloc] init];
    // 定制外观
    mgr.naviBgColor = [UIColor whiteColor];
    mgr.naviTitleColor = [UIColor blackColor];
    mgr.naviTitleFont = [UIFont boldSystemFontOfSize:18.0f];
    mgr.barItemTextColor = [UIColor blackColor];
    mgr.barItemTextFont = [UIFont systemFontOfSize:15.0f];
    mgr.statusBarStyle = UIStatusBarStyleDefault;
    ///是否需要录像
    mgr.allowTakeVideo = NO;
    ///选择图片
    mgr.allowPickingImage = YES;
    //  _mgr.allowPickingGif = YES;
    mgr.maxImageSelected = 1;
    mgr.videoMaximumDuration = 15;
    mgr.pickerSource = type;
    mgr.didFinishPickingBlock = ^(NSArray<ACMediaModel *> * _Nonnull list) {
        dispatch_async(dispatch_get_main_queue(), ^{
            block(list);
        });
    };
    [mgr picker];
    self.m = mgr;
    return mgr;
}
///随意点击关闭键盘
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}


- (UIStatusBarStyle)preferredStatusBarStyle {
    return  self.StatusBarColor ? UIStatusBarStyleLightContent : UIStatusBarStyleDefault;
}

-(void)didReceiveMemoryWarning{
    ///收到内存警告就清内存
    [super didReceiveMemoryWarning];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
    });
}
- (BOOL)shouldAutorotate {
    return NO;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}
- (void)dealloc {
    NSLog(@"被释放:%@",self.class);
}

@end


@implementation UIColor (Gradient)

+ (instancetype)gradientColorWithSize:(CGSize)size
                            direction:(GradientColorDirection)direction
                           startColor:(UIColor *)startcolor
                             endColor:(UIColor *)endColor {
    
    if (CGSizeEqualToSize(size, CGSizeZero) || !startcolor || !endColor) {
        return nil;
    }
    
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = CGRectMake(0, 0, size.width, size.height);
    
    CGPoint startPoint = CGPointMake(0.0, 0.0);
    if (direction == GradientColorDirectionUpwardDiagonalLine) {
        startPoint = CGPointMake(0.0, 1.0);
    }
    
    CGPoint endPoint = CGPointMake(0.0, 0.0);
    switch (direction) {
        case GradientColorDirectionVertical:
            endPoint = CGPointMake(0.0, 1.0);
            break;
        case GradientColorDirectionDownDiagonalLine:
            endPoint = CGPointMake(1.0, 1.0);
            break;
        case GradientColorDirectionUpwardDiagonalLine:
            endPoint = CGPointMake(1.0, 0.0);
            break;
        default:
            endPoint = CGPointMake(1.0, 0.0);
            break;
    }
    gradientLayer.startPoint = startPoint;
    gradientLayer.endPoint = endPoint;
    
    gradientLayer.colors = @[(__bridge id)startcolor.CGColor, (__bridge id)endColor.CGColor];
    UIGraphicsBeginImageContext(size);
    [gradientLayer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return [UIColor colorWithPatternImage:image];
}

@end

@implementation UIGTapGestureRecognizer
@end
